﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccess
{
    public class BorrowRecordService
    {
        private static readonly BorrowRecordService m_BorrowRecordService = new BorrowRecordService();
        private DataAccess.BooksContext Ctx
        {
            get
            {
                return new BooksContext();
            }
        }

        public static BorrowRecordService Instance
        {
            get { return m_BorrowRecordService; }
        }
        

        /// <summary>
        /// 通过用户ID查询记录
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public List<Books.Models.BorrowRecord> GetBRByUserId(int UserId)
        {
            using (var db = this.Ctx)
            {
                var item = db.BorrowRecords.Where(c=>c.UserID== UserId).ToList();
                return item;
            }
        }

        /// <summary>
        /// 通过书本ID查询记录
        /// </summary>
        /// <param name="BookId"></param>
        /// <returns></returns>
        public List<Books.Models.BorrowRecord> GetBRByBookId(int BookId)
        {
            using (var db = this.Ctx)
            {
                var item = db.BorrowRecords.Where(c => c.BookID == BookId).ToList();
                return item;
            }
        }


        /// <summary>
        /// 通过用户ID 和借阅ID借书
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="bookId"></param>
        /// <returns></returns>
        public string BorrowBook(int userId,int bookId)
        {
            using(var db=this.Ctx)
            {
                var book = db.Books.FirstOrDefault(c => c.BookId == bookId);
                if(book.Available==0)
                {
                    return "库存不足";
                }
                Books.Models.BorrowRecord borrow = new Books.Models.BorrowRecord();
                //赋值ID
                borrow.BookID = bookId;
                borrow.UserID = userId;
                //设置借阅时间和最迟归还时间
                borrow.BorrowDate = DateTime.Now;
                borrow.DueDate = DateTime.Now.AddMonths(1);
                //默认为续借 且只能续借一次
                borrow.IsRenewed = false;

                db.BorrowRecords.Add(borrow);
            }
            return "借阅成功";
        }

    }
}
